package com.googlecode.maratische.google.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import com.googlecode.maratische.google.BaseException;
import com.googlecode.maratische.google.DaoAction;

public class CommandUpdateFullItem extends CommandUpdateItemMedia {
	static Logger logger = Logger.getLogger(CommandUpdateFullItem.class.getName());

	@Override
	public String getType() {
		return Commands.UpdateFullItem.toString();
	}
	
	@Override
	public boolean execute(DaoAction daoAction) throws SQLException, BaseException {
		Item item = daoAction.getItemDao().get(this.getInteger1());
		String url = item.getLink();
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
		int status;
		try {
			status = httpClient.executeMethod(getMethod);
			if (status == 200) {
				InputStream inputStream = getMethod.getResponseBodyAsStream();
				String fileName = null;
//				do {
					fileName = getLocalMediaFileName(daoAction,"starred.html",getInteger1().toString());
//					logger.info("downloaded to "+fileName);
//				} while (new File(fileName).exists());
				FileOutputStream fos = new FileOutputStream(fileName);
				byte buf[]=new byte[1024];
			    int len;
			    while((len=inputStream.read(buf))>0) {
			    	fos.write(buf,0,len);
			    }
			    fos.close();
			    inputStream.close();
			    //TODO пометить что скачали!
			    Label label = DaoAction.getDaoAction().getLabelDao().get(item.getLabelId());
			    label.setFileSaved(fileName);
			    daoAction.getLabelDao().save(label);
				return true;
			}
		} catch (HttpException e) {
			throw new BaseException(e.getMessage());
		} catch (IOException e) {
			throw new BaseException(e.getMessage());
		}
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Integer getPriority() {
		return 4;
	}

}
